<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>URL.createObjectURL 图片视频上传 预览格式为Blob </title>
		<style type="text/css">
			.imgshow {
				padding: 1%;
				border: 1% antiquewhite;
				transition: background 1s;
				-moz-transition: background 1s;
				-webkit-transition: background 1s;
				-o-transition: background 1s;
			}
			.imgshow:hover {
				border: darkred;
				background: rgba(0, 0, 0, 0.2);
				}
			input[type=file] {
				top: 0;
				left: 0;
				width: 100px;
				height: 100px;
				overflow: hidden;
				/* cursor: pointer; */
				/*设置input不显示*/
				/* opacity: 0; */
				background: url(../img/24.png) round;
				cursor: pointer;
				/* 上面的代码是常规设置， 即：引入一个图片背景，设置在中心位置，大小和按钮的大小一致，以及鼠标指针为手型 */
				/*设置背景图片大小*/
				background-size: 100%;
				display: block;
				font-size: 0;
				line-height: 0;
				text-indent: -9999px;
			}
			input[type=file]:active {
				border: white;
			}
			.imgcontshow {
				visibility: hidden;
				opacity: 0;
				transform: scaleY(0);
				transition: .3s;
				animation: show .5s forwards;
			}
			@keyframes show {
				0% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(0)
				}
				40% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(1)
				}
				60% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(0)
				}
				80% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(2)
				}
				100% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(1)
				}
			}
			@keyframes fadenum {
				/*设置内容由显示变为隐藏*/
				0% {opacity: 0;}
				100% {opacity: 1;}
			}
		</style>
	</head>
	<body>
		<!-- 
		multiple="multiple"  开启多选
		maxsize  //设置文件上传的张数 
		accept // 设置文件选择的类型
		
		capture="camera" 相机  accept="image/*"  打开摄像头拍照
		
		capture="camcorder" 摄像机  accept="video/* 打开摄像头视频
		
		capture="microphone" 录音  accept="audio/*" 打开摄像头音频
		 -->
		<input type="file" multiple="" maxsize="50000"  accept="application/application/vnd.android.package-archive" />
		<div id="vessel"></div>
	</body>
	<script src="../js/inCommonUse.js" type="text/javascript" charset="utf-8"></script>
	
	
	<script type="text/javascript">
		// Ajax('post','http://60.10.165.110:8001/fbjd/msg/weather',{city:101090608})

		const imgs = document.querySelector('input[type=file]'); //获取file
		const vessel = document.getElementById('vessel');
		const filetype = imgs.getAttribute('datatype'); //获取自定义读取图片类型

		let imgsBlobArry = []; //存放blob数据
		let imgArrylist = []; //存放图片对象
		
		imgs.onchange = function update() {

			const typeFile = imgs.accept || imgs.accept.replace(/\s/g, "").split(",");
			console.log(imgs.files)
			for (let i = 0; i < imgs.files.length; i++) { //获取的图片放入数组

				console.log(imgs.files[i].type);
				if (parseInt(imgs.getAttribute("maxsize")) - 1 < i) {
					console.log("超出了数量");
					console.error('Exceeded number of custom files');
					break;
				}
				
				console.log(typeFile)
				// if (typeFile.indexOf(imgs.files[i].type) ===-1) { console.warn('上传文件类型有误'); continue; }

				let blobs = window.URL.createObjectURL(imgs.files[i]) //获取blob二进制数据，可用来显示
				imgArrylist.push(imgs.files[i]);
				imgsBlobArry.push({
					name: imgs.files[i].name,
					fileType: imgs.files[i].type,
					size: conver(imgs.files[i].size),
					uer: blobs,
					lastModifiedDate: imgs.files[i].lastModifiedDate
				});

				let TheLabel;
				if (String(imgs.files[i].type).includes('image')) {
					TheLabel = new Image;

				} else if (String(imgs.files[i].type).includes('video')) {
					TheLabel = document.createElement('video');
					
					          _this.video = _this.getObjectURL(fil); //这里是一个标识。可以忽略
					          var canvas = document.createElement("canvas"); //创建canvas对象
					          canvas.width = 300; //画布宽度
					          canvas.height = (300 * this.videoHeight) / this.videoWidth; //画布高度
					          canvas
					            .getContext("2d")
					            .drawImage(this, 0, 0, canvas.width, canvas.height); //绘制第一帧
					          setTimeout(() => { //这里为什么延迟到下次执行。因为有的时候。绘制不到。很奇怪。
					            document.getElementById("video-poster").src = canvas.toDataURL();

				} else if (String(imgs.files[i].type).includes('audio')) {
					TheLabel = new Audio;

				} else { //其他文件
					TheLabel = document.createElement('div');
				}

				let imgCont = document.createElement('div'); //最外层div
				let close = document.createElement('p'); //最外层div
				let progress = document.createElement('div'); // 显示进度条div
				close.className = 'close';
				close.style = `text-align: end;line-height: 0;cursor: pointer;`;
				close.innerHTML = `X`;

				TheLabel.style = `width:10rem;height:10rem`;
				TheLabel.src = blobs;
				TheLabel.id = "examine";
				imgCont.className = "imgshow imgcontshow";
				imgCont.style = `width: 10%;height: 10%;float: left;`;
				progress.style = `width:100%;height:0.2rem;background:#10affb`;

				if (progress.tagName === 'DIV') {
					TheLabel.innerHTML = `<img src="../img/file.jpg" alt="文件" style="width: 100%;">`
				}	
				imgCont.appendChild(close);
				imgCont.appendChild(TheLabel);

				imgCont.appendChild(progress);
				vessel.appendChild(imgCont);
				
				// postJSON('http://localhost:3692/imgeblob',{city:imgsBlobArry}).then()
				// postJSON('http://localhost:3692/imgeblob',{city:blobs}).then()
				// window.URL.revokeObjectURL(blobs) //手动回收
			}
		
			// console.log(imgsBlobArry)

			if (imgsBlobArry.length > parseInt(imgs.getAttribute("maxsize"))) {
				console.log("超出数量")
				imgs.style.display = 'none';

			} else {
				imgs.style.display = "table";
			}


			function conver(limit) { //图片大小 mb 换算
				let size = "";
				if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
					size = limit.toFixed(2) + "B";
				} else if (limit < 0.1 * 1024 * 1024) { //如果小于0.1MB转化成KB
					size = (limit / 1024).toFixed(2) + "KB";
				} else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
					size = (limit / (1024 * 1024)).toFixed(2) + "MB";
				} else { //其他转化成GB
					size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
				}
				let sizestr = size + "";
				let len = sizestr.indexOf("\.");
				let dec = sizestr.substr(len + 1, 2);
				if (dec === "00") { //当小数点后为00时 去掉小数部分
					return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
				}
				return sizestr;
			}
		}


		//点击图片查看
		var el = window.document.body; //声明一个变量，默认值为body
		window.document.body.onclick = function(event) {
			if (event.target.id === "") {
				if (event.target.id === 'showimg' || event.target.parentNode.id === 'showimg') {
					document.body.removeChild(document.getElementById('showimg'))
				}
			}
			let lookOver = document.getElementById('imgShow');
			if (event.target.tagName === 'IMG' || event.target.tagName === 'VIDEO' || event.target.tagName === 'Audio') {

				let showimg = event.target.tagName === "IMG" ? new Image : event.target.tagName === "VIDEO" ? document.createElement(
					'video') : new Audio;
				showimg.autoplay = true
				showimg.controls = true
				let divshow = document.createElement('div');
				showimg.style =
					`position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);animation: fadenum 2s forwards`;
				showimg.src = event.target.src;
				divshow.id = 'showimg';
				divshow.style = `position: fixed;top: 0px;width: 100%;height: 100%;background: rgba(0,0,0,0.1);text-align:center;`

				divshow.appendChild(showimg)

				if (!lookOver) {
					document.body.appendChild(divshow)
				}

			}

			if (event.target.id === 'showimg' || event.target.parentNode.id === 'showimg') {
				document.body.removeChild(document.getElementById('showimg'))
			}


			if (event.target.tagName === 'P') {
				document.querySelectorAll('.close').forEach((tiem, index) => {
					tiem.onclick = function() {
						console.log(this.parentNode);
						document.getElementById('vessel').removeChild(this.parentNode);
						imgsBlobArry.splice(index, 1);

						console.log(imgsBlobArry)
					}
				});
				if (imgsBlobArry.length > parseInt(imgs.getAttribute("maxsize"))) {
					console.log("超出数量")
					imgs.style.display = 'none';

				} else {
					imgs.style.display = "table";
				}
			}
		};
		
		
		
		function postJSON(url, data) {
		    return new Promise( (resolve, reject) => {
		        var xhr = new XMLHttpRequest()
		        xhr.open("POST", url, true)
				xhr.datatype = 'json'
		        xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		
		        xhr.onreadystatechange = function () {
		            if (this.readyState === 4) {
		                if (this.status === 200) {
		                    resolve(JSON.parse(this.responseText), this)
		                } else {
		                    var resJson = { code: this.status, response: this.response }
		                    reject(resJson, this)
		                }
		            }
		        }
		        xhr.send(JSON.stringify(data))
		    })
		}
	</script>
</html>
